package com.hundsun.fcp.webplugin.service.update;

import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.http.Header;
import org.apache.http.client.HttpResponseException;
import org.apache.http.conn.ConnectTimeoutException;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.hundsun.fcp.common.logger.AndroidLogger;
import com.hundsun.fcp.common.logger.Logger;
import com.hundsun.fcp.webplugin.bean.UpdateManifestBean;
import com.hundsun.fcp.webplugin.service.ErrorCode;
import com.hundsun.fcp.webplugin.service.FcpDataServiceBase;

public class FcpUpdateManifestDataService extends FcpDataServiceBase {
	private static final Logger LOGGER = AndroidLogger.getLogger() ;
	private AtomicReference<UpdateManifestBean> cache = new AtomicReference(null);

	protected FcpUpdateManifestDataService(Context pContext) {
		super(pContext);
	}
	
	public static FcpUpdateManifestDataService create(Context pContext)
	{
		return new FcpUpdateManifestDataService(pContext);
	}

	@Override
	public void get(Object pObject) {

	}

	@Override
	protected String getRequestURL(String pStr) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void post(Object pObject) {
	    this.cache.set(null);
	    getAsyncHttpClient().post(getContext(), getRequestURL(null), null, this);
	}

	@Override
	public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
		try {
			String result = new String(responseBody,"utf-8");
			UpdateManifestBean _UpdateManifestBean = JSON.parseObject(result, UpdateManifestBean.class) ;
			if(getCallBack()!=null){
				getCallBack().onGetData(_UpdateManifestBean) ;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onFailure(int statusCode, Header[] headers,
			byte[] responseBody, Throwable error) {
		if(statusCode==304){
			LOGGER.debug("304 Not Modified") ;
			if(cache.get()!=null){
				UpdateManifestBean _UpdateManifestBean = (UpdateManifestBean)this.cache.get();
				if (getCallBack() != null) {
					getCallBack().onGetData(_UpdateManifestBean);
				}
			}
		}else{
			int _ErrorCode = ErrorCode.SOCKET_ERROR ;
			try{
			    if (error instanceof HttpResponseException) {
			    	_ErrorCode = ((HttpResponseException)error).getStatusCode();
			    }
			    if(error instanceof SocketTimeoutException){
			    	_ErrorCode = ErrorCode.SOCKET_TIMEOUT ;
			    }
			    if(error instanceof ConnectTimeoutException){
			    	_ErrorCode = ErrorCode.CONNECT_TIMEOUT ;
			    }
			    String errorMsg = new String(responseBody);
			    HandleError(_ErrorCode, errorMsg==null?"":errorMsg, error);
			}catch(Exception e){
				 HandleError(_ErrorCode, "网络连接连接错误", error);
			}
		}
	}

}
